import React from "react";
import G2 from "bizcharts/node_modules/@antv/g2/src";
import { Debounce } from "../../../common/core/decorator";
import { service } from "../service/service";
import { confSrore } from "../service/store";

interface IProps {
  name: string
}

class State {
  public height: 250
}

export default class ChartA extends React.Component<IProps> {
  public static info = {
    name: "ChartA",
    sourceUrl: 'https://www.easy-mock.com/mock/5b55575020511b117b20c758/example/chartsData',
    formater: 'data'
  }

  public state = new State()

  private ref: any
  private chart: G2.Chart

  public componentDidMount() {
    const data: any[] = [
      // { genre: 'Sports', sold: 275 },
    ];

    const chart = new G2.Chart({
      container: this.ref,
      width: 250,
      height: 250
    });

    chart.source(data);
    chart.interval().position('genre*sold').color('genre');
    chart.render();
    this.chart = chart
    confSrore.subscribe(_ => {
      this.setData()
    })
  }

  public render() {
    return <div ref={(ref) => this.ref = ref} style={{ height: '100%' }} />
  }

  public async componentDidUpdate() {
    this.chart.changeSize(this.ref.clientWidth, this.ref.clientHeight)
  }

  @Debounce(500)
  private async setData() {
    const chartConf = service.getItemConf(this.props.name) || ChartA.info
    let data = await fetch(ChartA.info.sourceUrl).then(res => res.json())
    data = eval(chartConf.formater)
    this.chart.changeData(data.map((x: any) => {
      return {
        genre: Object.keys(x)[0],
        sold: x[Object.keys(x)[0]]
      }
    }))
  }
}